package com.wms.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wms.pojo.Category;
import com.wms.pojo.Company;
import com.wms.pojo.Wine;
import com.wms.service.CategoryService;
import com.wms.service.CompanyService;
import com.wms.service.WineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/wine")
public class WineController {

    @Autowired
    private WineService wineService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private CompanyService companyService;

    @GetMapping("/getWines")
    public String getWines(@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "5") Integer pageSize, Model model){
        PageHelper.startPage(pageNum,pageSize);
        List<Wine> wines = wineService.queryAll();
        PageInfo pageInfo = new PageInfo(wines);
        model.addAttribute("pageInfo",pageInfo);
        return "wine/wine-list";
    }

    @GetMapping("/editWine")
    public String editWine(@RequestParam("id") Integer id,Model model){
        Wine wine = wineService.queryById(id);
        List<Category> categories = categoryService.queryAll();
        List<Company> companies = companyService.queryAll();
        model.addAttribute("categories",categories);
        model.addAttribute("companies",companies);
        model.addAttribute("wine",wine);
        return "wine/wine-edit";
    }

    @PostMapping("/saveWine")
    public String saveWine(Wine wine){
        wineService.updateWine(wine);
        return "redirect:/wine/getWines";
    }

    @GetMapping("/deleteWine")
    public String deleteWine(@RequestParam("id") Integer id){
        wineService.deleteWine(id);
        return "redirect:/wine/getWines";
    }

    @GetMapping("/toAdd")
    public String toAdd(Model model){
        List<Company> companies = companyService.queryAll();
        List<Category> categories = categoryService.queryAll();
        model.addAttribute("companies",companies);
        model.addAttribute("categories",categories);
        return "wine/wine-edit-block";
    }

    @PostMapping("/addWine")
    public String addWine(Wine wine){
        wineService.addWine(wine);
        return "redirect:/wine/getWines";
    }
}
